require 'rubygems'
require 'xmpp4r'
require 'xmpp4r-simple'
require 'digest/sha1'


module Xmpp
    Workers = {}

    class JabberSession
        def initialize(jid, password)
            begin
                @session = Jabber::Simple.new(jid, password)
                @uuid = Digest::SHA1.hexdigest(jid + password)
                @roster = get_roster()
                Xmpp::Workers[@uuid] = self
            rescue AuthenticationFailure => e
                puts e
            end
        end

        def uuid()
            return @uuid
        end

        def add(jid)
            return @session.add(jid)
        end

        def remove(jid)
            return @session.remove(jid)
        end

        def subscribe(jid)
            return @session.add(jid)
        end

        def unsubscribe(jid)
            return @session.remove(jid)
        end

        def authorize(jid)
        end

        def send(jid, message)
            return @session.deliver(jid, message)
        end

        def decline(jid)
        end

        def roster()
            return @session.roster.items
        end

        def get_roster()
            while @session.roster.items.size == 0
                sleep 0.5
            end
            @roster = @session.roster
        end
    end
end
